<?php

class Price extends M_Controller {

    private function _get_price($price, $config) {


        $value = $config['type'] == 1 ? $config['vaue'] : -$config['vaue'];

        if ($config['fs'] == 1) {
            // 固定
            return max(0, $price - $value);
        } else {
            // 百分百
            return max(0, $price + $price * $value/100);
        }
    }

	public function index() {

		if (IS_POST) {
			$data = $this->input->post('data', TRUE);
            if (!$data['type']) {
                $this->_json(0, fc_lang('批量方式未选择'));
            } elseif (!$data['vaue']) {
                $this->_json(0, fc_lang('没有输入变更值'));
            }

            if (!$data['ids']) {
                $list = \Poscms\Service::M()->table(SITE_ID.'_'.APP_DIR)->getAll();
            } else {
                $list = \Poscms\Service::M()->table(SITE_ID.'_'.APP_DIR)->where_in('id', $data['ids'])->getAll();
            }

			if (!$list) {
                $this->_json(0, fc_lang('无可用变更商品'));
            }

            foreach ($list as $t) {

			    $save = array(
			      'order_price' => $this->_get_price($t['order_price'], $data)
                );
			    $sku = dr_string2array($t['order_specification']);
			    if ($sku) {
			        foreach ($sku['value'] as $i => $v) {
			            $sku['value'][$i]['price'] = $this->_get_price($v['price'], $data);
                    }
                    $save['order_specification'] = dr_array2string($sku);
                }

                \Poscms\Service::M()->table(SITE_ID.'_'.APP_DIR)->update($t['id'], $save);
            }

            $this->_json(1, fc_lang('变更%s个商品价格', count($list)));
		}

        $field = array(
            'ids' => array(
                'ismain' => 1,
                'name' => '选择商品',
                'fieldname' => 'ids',
                'fieldtype' => 'Related',
                'setting' => array(
                    'option' => array(
                        'module' => APP_DIR,
                    )
                )
            )
        );
		
		$this->template->assign(array(
            'menu' => $this->get_menu_v3(array(
                fc_lang('批量改价') => array(APP_DIR.'/admin/price/index', 'rmb'),
            )),
            'type' => array(
                '1' => fc_lang('增加价格'),
                '-1' => fc_lang('减少价格'),
            ),
            'field' => dr_field_input('ids', 'Related', $field['ids']['setting']),
		));
		$this->template->display('price.html');
	}
	

	
}